﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProductKeyManager.DB;
using System.Windows;
using System.IO;

namespace ProductKeyManager.Xml
{
    /// <summary>
    /// A static class to help with XML tasks.
    /// </summary>
    public static class XmlHelper
    {
        /// <summary>
        /// Imports the XML.
        /// </summary>
        /// <param name="fileUri">The file URI.</param>
        /// <returns></returns>
        public static IXmlHandler ImportXml(Uri fileUri)
        {
            IXmlHandler handler;
            try
            {
                handler = new ProductKeyManagerXmlHandler();
                handler.ImportXml(fileUri);
            }
            catch (NullReferenceException)
            {
                handler = new MsdnXmlHandler();
                handler.ImportXml(fileUri);
            }

            return handler;
        }

        /// <summary>
        /// Saves the product key XML.
        /// </summary>
        /// <param name="generateStyleSheet">if set to <c>true</c> [generate style sheet].</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="xml">The XML.</param>
        /// <param name="xmlStyleSheet">The XML style sheet.</param>
        public static void SaveProductKeyXml(bool generateStyleSheet, string fileName, string xml, string xmlStyleSheet)
        {
            File.WriteAllText(fileName, xml, Encoding.Default);
            if (generateStyleSheet)
            {
                if (File.Exists(fileName + ".xsl"))
                {
                    if (MessageBox.Show("'" + fileName + ".xsl?' already exists." + Environment.NewLine + "Do you want to replace it?", "Save As", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                    {
                        File.WriteAllText(fileName + ".xsl", xmlStyleSheet, Encoding.Default);
                    }
                }
                else
                {
                    File.WriteAllText(fileName + ".xsl", xmlStyleSheet, Encoding.Default);
                }
            }
        }
    }
}